package com.youthfilmic.yuejian.weixin.pay;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.UUID;

import com.youthfilmic.yuejian.conn.WeixinConn;
import com.youthfilmic.yuejian.util.HttpUtil;
import com.youthfilmic.yuejian.util.MD5Util;
import com.youthfilmic.yuejian.util.XMLUtil;
import com.youthfilmic.yuejian.weixin.core.ResultConfig;
import net.sf.json.JSONObject;

/**
 * @title 统一下单接口
 * @author youweixi
 * @time 2015.7.12
 * */
public class UnifiedOrder {
	// 随机字符串
	private String nonce_str = null;
	// 商品描述
	private String body = null;
	// 商户订单号（需要唯一）
	private String out_trade_no = null;
	// 总金额，只能是整数，以分为单位不含小数点
	private int total_fee = 1;
	// 终端ip
	private String spbill_create_ip = null;
	// 微信用户唯一标识
	private String openid = null;
	// 返回结果
	private JSONObject jsonResult = null;


	public UnifiedOrder(String userOpenId , int price , String body,String out_trade_no ) {
		total_fee = Integer.parseInt(String.format("%.2f", Float.parseFloat(String.valueOf(price))).replace(".", ""));
		// 随机字符串，这里用UUID来生成，注意UUID里面包含‘-’
		nonce_str = UUID.randomUUID().toString().replace("-","");
		spbill_create_ip = "182.92.220.150";
		openid = userOpenId;
		SortedMap<String, String> packageParams = new TreeMap<String, String>();
		packageParams.put("appid", WeixinConn.APP_ID);
		packageParams.put("mch_id", WeixinConn.WEIXIN_MCH_ID);
		packageParams.put("nonce_str", nonce_str);
		packageParams.put("body", body);
		packageParams.put("out_trade_no", out_trade_no);
		packageParams.put("total_fee", String.valueOf(total_fee));
		packageParams.put("spbill_create_ip", spbill_create_ip);
		packageParams.put("notify_url", WeixinConn.WEIXIN_PAY_NOTIFY_URL);
		packageParams.put("trade_type", WeixinConn.WEIXIN_PAY_TRADE_TYPE);
		//packageParams.put("trade_type", "NATIVE");
		packageParams.put("openid", openid);
		// 注意这里生成sign参数的时候不包括sign
		packageParams.put("sign", WeixinPayAPI.createSign(packageParams));
		// 将map转变为xml标准字符串
		String xml = XMLUtil.getXMLFromMap("xml", packageParams);
		JSONObject json = HttpUtil.httpRequestFromXml(WeixinConn.WEIXIN_PAY_URL, "POST", xml);
		System.out.println(json.toString());
		if (json.containsKey("return_code")
				&& "SUCCESS".equals(json.get("return_code"))
				&& json.containsKey("result_code")
				&& "SUCCESS".equals(json.get("result_code"))) {
			json.put("status", ResultConfig.STATUS_GLOBAL_SUCCEED);
			json.put("msg", "fetch ok");
			SortedMap<String, String> finalpackage = new TreeMap<String, String>();
			String timestamp = WeixinPayAPI.getTimeStamp();
			String packages = "prepay_id=" + json.getString("prepay_id");
			finalpackage.put("appId", WeixinConn.APP_ID);
			finalpackage.put("timeStamp", timestamp);// 注意这里是大写S，但是微信前端需要签名的时候需要的是timestamp
			finalpackage.put("nonceStr", nonce_str);
			finalpackage.put("package", packages);
			finalpackage.put("signType", "MD5");
			String finalsign = WeixinPayAPI.createSign(finalpackage);
			json.put("sign", finalsign);
			json.put("nonce_str", nonce_str);
			json.put("timestamp", timestamp);
		} else {
			json.put("status", ResultConfig.STATUS_GLOBAL_NOT_KNOWN_WRONG);
			json.put("msg", "something wrong");
		}
		this.jsonResult = json;
	}


	public static void main(String[] args) {
		UnifiedOrder pill =new UnifiedOrder("oVw7Lt7rswjfOPXcghFk6GMP0xmU" , 1 , "新鲜的墨鱼" , "jkhrkjef3");
		System.out.println(pill.getJsonResult().toString());
	}

	public JSONObject getJsonResult() {
		return jsonResult;
	}

	public void setJsonResult(JSONObject jsonResult) {
		this.jsonResult = jsonResult;
	}

	// 生成sign之前需要的字段
	// String sign = createSign(packageParams);
	/*
	 * String xml="<?xml version=\"1.0\" encoding=\"UTF-8\"?><xml>"+
	 * "<appid>"+appid+"</appid>"+ "<mch_id>"+mch_id+"</mch_id>"+
	 * "<nonce_str>"+nonce_str+"</nonce_str>"+ "<sign>"+sign+"</sign>"+
	 * "<body><![CDATA["+body+"]]></body>"+
	 * "<out_trade_no>"+out_trade_no+"</out_trade_no>"+
	 * "<total_fee>"+total_fee+"</total_fee>"+
	 * "<spbill_create_ip>"+spbill_create_ip+"</spbill_create_ip>"+
	 * "<notify_url>"+notify_url+"</notify_url>"+
	 * "<trade_type>"+trade_type+"</trade_type>"+ "<openid>"+openid+"</openid>"+
	 * "</xml>";
	 */

}
